﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace NSR.HD.Common
{
    public class Serialize
    {

        /// <summary>
        /// 需要序列化XML数据对象
        /// </summary>
        /// <param name="objectToSerialize"></param>
        /// <returns></returns>
        public static string XMLSerialize(object objectToSerialize)
        {
            string result = "";
            using (MemoryStream ms = new MemoryStream())
            {
                DataContractSerializer serializer = new DataContractSerializer(objectToSerialize.GetType());
                serializer.WriteObject(ms, objectToSerialize);
                ms.Position = 0;

                using (StreamReader reader = new StreamReader(ms))
                {
                    result = reader.ReadToEnd();
                }
            }
            return result;
        }


        ///// <summary> 
        ///// XML数据反序列化
        ///// </summary>
        ///// <param name="xmlstr"></param>
        ///// <returns></returns>
        //public static T XMLDeserialize(string xmlstr)
        //{
        //    byte[] newBuffer = System.Text.Encoding.UTF8.GetBytes(xmlstr);

        //    if (newBuffer.Length == 0)
        //    {
        //        return default(T);
        //    }
        //    using (MemoryStream ms = new MemoryStream(newBuffer))
        //    {
        //        DataContractSerializer serializer = new DataContractSerializer(typeof(T));
        //        return (T)serializer.ReadObject(ms);
        //    }
        //}
    }
}